package com.jh.complicate.rpc.v2.server;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Administrator
 * @projectName newforward
 * @title RPCService.java
 * @package com.jh.complicate.rpc.v2.server
 * @description
 * @date 2019/6/12 13:35
 */
@Component(value = "rpcService")
public class RPCService implements ApplicationContextAware, InitializingBean {

    ExecutorService executorService = Executors.newCachedThreadPool();

    Map<String, Object> handlerMap = new HashMap<>();

    private int port;

    public RPCService(int port) {
        this.port = port;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            // 不断接收请求
            while (true) {
                // BIO阻塞获取请求
                Socket socket = serverSocket.accept();

                // 提交任务到线程池处理
                executorService.submit(new ProcessorHandler(handlerMap, socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != serverSocket) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> baenMap = applicationContext.getBeansWithAnnotation(RPCServer.class);
        if (!baenMap.isEmpty()) {
            for (Object bean : baenMap.values()) {
                RPCServer annotation = bean.getClass().getAnnotation(RPCServer.class);
                String beanName = annotation.value().getName();
                String version = annotation.version();
                if (!StringUtils.isEmpty(version)) {
                    beanName += "-" + version;
                }

                handlerMap.put(beanName, bean);
            }
        }
    }

}
